package com.ruoyi.cm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.base.domain.BaseBsZd;
import com.ruoyi.base.mapper.BaseBsBdMapper;
import com.ruoyi.base.mapper.BaseBsZdMapper;
import com.ruoyi.cm.domain.*;
import com.ruoyi.cm.domain.bo.CmBsStartAdvanceBo;
import com.ruoyi.cm.domain.vo.*;
import com.ruoyi.cm.mapper.*;
import com.ruoyi.cm.service.ICmBsStartAdvanceService;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.ruoyi.cm.domain.bo.CmBdQsCountBo;
import com.ruoyi.cm.service.ICmBdQsCountService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 标段期数计算Service业务层处理
 *
 * @author zxs
 * @date 2024-09-30
 */
@RequiredArgsConstructor
@Service
public class CmBdQsCountServiceImpl implements ICmBdQsCountService {

    private static Logger logger = LoggerFactory.getLogger(CmBdQsCountServiceImpl.class);

    private final CmBdQsCountMapper baseMapper;

    private final CmBsQsMapper qsMapper;

    private final BaseBsZdMapper zdMapper;

    private final BaseBsBdMapper bdMapper;
    //中间计量
    private final CmPeriodMeasurementMapper periodMapper;
    //其他计量
    private final CmBaSettleDeductDetailMapper deductDetailMapper;
    //开工预付款
    private final CmBsStartAdvanceMapper advanceMapper;
    //报表管理
    private final CmReportMapper reportMapper;

    private final ICmBsStartAdvanceService advanceService;

    /**
     * 查询标段期数计算
     */
    @Override
    public CmBdQsCountVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询标段期数计算列表
     */
    @Override
    public TableDataInfo<CmBdQsCountVo> queryPageList(CmBdQsCountBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CmBdQsCount> lqw = buildQueryWrapper(bo);
        Page<CmBdQsCountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询标段期数计算列表
     */
    @Override
    public List<CmBdQsCountVo> queryList(CmBdQsCountBo bo) {
        LambdaQueryWrapper<CmBdQsCount> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CmBdQsCount> buildQueryWrapper(CmBdQsCountBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CmBdQsCount> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getBdId() != null, CmBdQsCount::getBdId, bo.getBdId());
        lqw.eq(bo.getQsId() != null, CmBdQsCount::getQsId, bo.getQsId());
        lqw.eq(bo.getZdId() != null, CmBdQsCount::getZdId, bo.getZdId());
        lqw.eq(bo.getBbglId() != null, CmBdQsCount::getBbglId, bo.getBbglId());
        lqw.eq(bo.getBqjlje() != null, CmBdQsCount::getBqjlje, bo.getBqjlje());
        lqw.eq(bo.getLjjlje() != null, CmBdQsCount::getLjjlje, bo.getLjjlje());
        lqw.eq(bo.getBqzfje() != null, CmBdQsCount::getBqzfje, bo.getBqzfje());
        lqw.eq(bo.getLjzfje() != null, CmBdQsCount::getLjzfje, bo.getLjzfje());
        lqw.eq(bo.getStatus() != null, CmBdQsCount::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增标段期数计算
     */
    @Override
    public Boolean insertByBo(CmBdQsCountBo bo) {
        CmBdQsCount add = BeanUtil.toBean(bo, CmBdQsCount.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改或新增标段期数计算
     * 本期计量金额 = 每站点当期计量金额(合价)合计
     * 累计计量金额 = 已计量期数的本期计量金额合计
     * 本期支付金额 = 本期计量金额-扣回开工预付金额+奖罚金
     * 累计支付金额 = 开工预付款-奖励基金 + 已计量期数的本期支付金额合计
     */
    @Override
    public Boolean updateByBo(CmBdQsCountBo bo) {
        CmBdQsCount update = BeanUtil.toBean(bo, CmBdQsCount.class);
//        validEntityBeforeSave(update);
        Long bdId = bo.getBdId();
        Long qsId = bo.getQsId();
        if (bdId == null) {
            return false;
        }
        //查询当前标段下站点；
        LambdaQueryWrapper<BaseBsZd> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseBsZd::getBdId, bdId);
        lqw.eq(BaseBsZd::getDelFlag, 0);
        List<BaseBsZd> zdList = zdMapper.selectList(lqw);
        //查询当前标段下期数；
        LambdaQueryWrapper<CmBsQs> wraper = new LambdaQueryWrapper<>();
        wraper.eq(CmBsQs::getBdId,bdId);
        wraper.eq(CmBsQs::getDelFlag,0);
        List<CmBsQs> qsList = qsMapper.selectList(wraper);
        //根据标段查询标段期数计算值列表；
        LambdaQueryWrapper<CmBdQsCount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmBdQsCount::getBdId,bdId);
        List<CmBdQsCount> cmBdQsCounts = baseMapper.selectList(wrapper);

        //todo

        return baseMapper.insertOrUpdateBatch(cmBdQsCounts);
    }

//       本期计量金额 = 本站点当期计量金额(合价)合计 =206729.87-60648
//     * 累计计量金额 = 已计量期数的本期计量金额合计
//     * 本期支付金额 = 本期计量金额-扣回开工预付金额+奖罚金-多开票
//     * 本期支付金额 = 本期开工预付款-本期奖励基金 + 本期计量金额-扣回开工预付金额 + 奖罚金-多开票   2025/3/28调整；
//     * 累计支付金额 = 开工预付款-奖励基金 + 已计量期数的本期支付金额合计
//     * 累计支付金额 = 已计量期数的本期支付金额合计   2025/3/28调整；
    //更新或新增标段站点期数计算值；
    @Override
    @DSTransactional
    public Boolean update(CmBdQsCountBo bo) {
        Long bdId = bo.getBdId();
        Long zdId = bo.getZdId();
        Long qsId = bo.getQsId();
        if(bdId == null || zdId == null || qsId == null){
            return false;
        }
        //1.查询标段下的所有期数；
        List<CmBsQs> qsList = qsMapper.selectList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId,bdId));
        if(CollUtil.isEmpty(qsList)){
            return false;
        }
        //本期期数；
        Integer qs = qsList.stream().filter(e -> qsId.equals(e.getQsId())).collect(Collectors.toList()).get(0).getSettleIndex();
        //往期期数id
        Set<Long> qqsIdSet = qsList.stream().filter(e -> e.getSettleIndex() <= qs).map(CmBsQs::getQsId).collect(Collectors.toSet());
        //2.查询该标段下的开工预付款
        //往期开工预付款(=本期及之前所有期次的)
        CmBsStartAdvanceVo wkgyfk = null ;
        CmBsStartAdvanceBo advanceBo = new CmBsStartAdvanceBo();
        advanceBo.setBdId(bdId);
        //本站点的开工预付款(所有期次)；
        List<CmBsStartAdvanceVo> advanceVos = advanceService.listData(advanceBo).stream().filter(e->zdId.equals(e.getZdId())).collect(Collectors.toList());
        //本站点往期开工预付款(包含本期)；
        List<CmBsStartAdvanceVo> qAdvanceVos = advanceVos.stream().filter(e->qqsIdSet.contains(e.getQsId())).collect(Collectors.toList());
        //往期开工预付款；
        BigDecimal wkgyfkjr = BigDecimal.ZERO;
        BigDecimal wkcjljj = BigDecimal.ZERO;
        if(CollUtil.isNotEmpty(qAdvanceVos)) {
            wkgyfk = qAdvanceVos.get(0);
            if (wkgyfk != null) {
                wkgyfkjr = wkgyfk.getKgyfkjr();
                wkcjljj = wkgyfk.getKcjljj();
            }
        }
        //3.查询中间计量列表
        LambdaQueryWrapper<CmPeriodMeasurement> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CmPeriodMeasurement::getZdId,zdId);
        lambdaQueryWrapper.eq(CmPeriodMeasurement::getQsId,qsId);
        List<CmPeriodMeasurement> cmPeriodMeasurements = periodMapper.selectList(lambdaQueryWrapper);
        BigDecimal bqjl = BigDecimal.ZERO;
        for(CmPeriodMeasurement vo :cmPeriodMeasurements) {
            if (vo.getTotalPrice() != null) {
                bqjl = BigDecimalUtil.add(bqjl, vo.getTotalPrice());
            }
        }
        //4.查询其他计量金额；
        LambdaQueryWrapper<CmBaSettleDeductDetail> qtjlWrapper = new LambdaQueryWrapper<>();
        qtjlWrapper.eq(CmBaSettleDeductDetail::getBdId,bdId);
        qtjlWrapper.eq(CmBaSettleDeductDetail::getQsId,qsId);
        List<CmBaSettleDeductDetail> qtjlList = deductDetailMapper.selectList(qtjlWrapper);
        BigDecimal khkgyfk = BigDecimal.ZERO;
        BigDecimal jfje = BigDecimal.ZERO;
        BigDecimal dkp = BigDecimal.ZERO;
        BigDecimal bqzfje;
        BigDecimal ljzfje = BigDecimal.ZERO;
        if(CollUtil.isNotEmpty(qtjlList)){
            qtjlList = qtjlList.stream().filter(e -> zdId.equals(e.getZdId())).collect(Collectors.toList());
            for(CmBaSettleDeductDetail qtjl : qtjlList){
                //扣回开工预付款；
                if("2".equals(qtjl.getDeductType())){
                    khkgyfk = qtjl.getDeductDetailMoney()== null ? BigDecimal.ZERO:qtjl.getDeductDetailMoney();
                }
                //奖罚金额；
                if("1".equals(qtjl.getDeductType())){
                    jfje = qtjl.getDeductDetailMoney() == null ? BigDecimal.ZERO:qtjl.getDeductDetailMoney();
                }
                // 替其他站多开票金额
                if ("3".equals(qtjl.getDeductType())) {
                    dkp = qtjl.getDeductDetailMoney() == null ? BigDecimal.ZERO:qtjl.getDeductDetailMoney();
                }
            }
            //本期支付金额；
            bqzfje= BigDecimalUtil.add(BigDecimalUtil.subtract(bqjl, khkgyfk).subtract(dkp), jfje);
        } else {
            bqzfje = bqjl;
        }
        //考虑开工预付款，放到本期支付金额里；
        List<CmBsStartAdvanceVo> curAdvance = advanceVos.stream().filter(e->qsId.equals(e.getQsId())).collect(Collectors.toList());
        if(CollUtil.isNotEmpty(curAdvance)){
            CmBsStartAdvanceVo advanceVo = curAdvance.get(0);
            bqzfje = BigDecimalUtil.add(BigDecimalUtil.subtract(advanceVo.getKgyfkjr(),advanceVo.getKcjljj()),bqzfje);
        }
        //5.计算数据；
        //根据站点id查询站点期数计算的数据
        LambdaQueryWrapper<CmBdQsCount> qsWrapper = new LambdaQueryWrapper<>();
        qsWrapper.eq(CmBdQsCount::getZdId,zdId);
        List<CmBdQsCount> qsCounts = baseMapper.selectList(qsWrapper);
        LambdaQueryWrapper<CmBdQsCount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmBdQsCount::getQsId,qsId);
        wrapper.eq(CmBdQsCount::getZdId,zdId);
        wrapper.eq(CmBdQsCount::getBdId,bdId);
        CmBdQsCount qsCount = baseMapper.selectOne(wrapper);
        if(qsCount == null){
            qsCount = new CmBdQsCount();
            qsCount.setQsId(qsId);
            qsCount.setZdId(zdId);
            qsCount.setBdId(bdId);
            qsCount.setQs(qs);
            qsCount.setBqjlje(bqjl);
            qsCount.setBqzfje(bqzfje);
            //判断是否是第一期
            if (qs == 1) {
                qsCount.setLjjlje(bqjl);
//                ljzfje = BigDecimalUtil.add(BigDecimalUtil.subtract(wkgyfkjr, wkcjljj), bqzfje);
                ljzfje =  bqzfje;
                qsCount.setLjzfje(ljzfje);
            } else {
                //如果不是第一期，查询所有往期的数据；
                List<CmBdQsCount> qqsCounts = qsCounts.stream().filter(e -> e.getQs() < qs).collect(Collectors.toList());
                BigDecimal ljjlje = BigDecimal.ZERO;
                for (CmBdQsCount count : qqsCounts) {
                    if (count.getBqzfje() != null) {
                        ljzfje = BigDecimalUtil.add(ljzfje, count.getBqzfje());
                    }
                    if (count.getBqjlje() != null) {
                        ljjlje = BigDecimalUtil.add(ljjlje, count.getBqjlje());
                    }
                }
//                ljzfje = BigDecimalUtil.add(bqzfje, BigDecimalUtil.add(ljzfje, BigDecimalUtil.subtract(wkgyfkjr, wkcjljj)));
                ljzfje = BigDecimalUtil.add(bqzfje, ljzfje);
                qsCount.setLjjlje(BigDecimalUtil.add(bqjl, ljjlje));
                qsCount.setLjzfje(ljzfje);
            }
        } else {
            //修改操作：
            // 1、修改本期四个基本字段值；（思路：a、本期计量和本期支付金额直接替换；b、累计计量和累计支付金额是旧数据的累计-旧数据的本次+新数据的本期即是新数据的累计计量或累计支付）
            // 2、按本期的四个字段值重新计算并修改大于本期次的累计支付的字段值

            //1、更新本期数据；
            //本期计量
            qsCount.setBqjlje(bqjl);
            //本期支付；
            qsCount.setBqzfje(bqzfje);
            //原累计支付金额
            BigDecimal yljzfje = qsCount.getLjzfje();
            //原累计计量金额
            BigDecimal yljjl = qsCount.getLjjlje();
            //判断是否是第一期
            if (qs == 1) {
                qsCount.setLjjlje(bqjl);
//                ljzfje = BigDecimalUtil.add(BigDecimalUtil.subtract(wkgyfkjr, wkcjljj), bqzfje);
                ljzfje = bqzfje;
                qsCount.setLjzfje(ljzfje);
            } else {
                //如果不是第一期，查询所有往期的数据；
                List<CmBdQsCount> qqsCounts = qsCounts.stream().filter(e -> e.getQs() < qs).collect(Collectors.toList());
                BigDecimal ljjlje = BigDecimal.ZERO;
                for (CmBdQsCount count : qqsCounts) {
                    if (count.getBqzfje() != null) {
                        ljzfje = BigDecimalUtil.add(ljzfje, count.getBqzfje());
                    }
                    if (count.getBqjlje() != null) {
                        ljjlje = BigDecimalUtil.add(ljjlje, count.getBqjlje());
                    }
                }
//                ljzfje = BigDecimalUtil.add(bqzfje, BigDecimalUtil.add(ljzfje, BigDecimalUtil.subtract(wkgyfkjr, wkcjljj)));
                ljzfje = BigDecimalUtil.add(bqzfje, ljzfje);
                qsCount.setLjjlje(BigDecimalUtil.add(bqjl, ljjlje));
                qsCount.setLjzfje(ljzfje);
            }
            //2.更新大于本期期数的数据；
            List<CmBdQsCount> greater = qsCounts.stream().filter(e -> e.getQs() > qs).collect(Collectors.toList());
            //计算大于当前期次的累计支付金额和累计计量金额变化；
            BigDecimal ljzfchanges = BigDecimalUtil.subtract(qsCount.getLjzfje(), yljzfje);
            BigDecimal ljjlchanges = BigDecimalUtil.subtract(qsCount.getLjjlje(), yljjl);
            //优化，如果累计支付金额和累计计量金额都没变化，则跳过更新操作；(jlch ==0 && zfch == 0)  ->false
            if (CollUtil.isNotEmpty(greater)) {
//            if (CollUtil.isNotEmpty(greater) && (ljjlchanges.compareTo(BigDecimal.ZERO) != 0 || ljzfchanges.compareTo(BigDecimal.ZERO) != 0)) {
                for (CmBdQsCount count : greater) {
                    count.setLjzfje(BigDecimalUtil.add(count.getLjzfje(), ljzfchanges));
                    count.setLjjlje(BigDecimalUtil.add(count.getLjjlje(), ljjlchanges));
                }
                baseMapper.updateBatchById(greater);
            }
        }
        return baseMapper.insertOrUpdate(qsCount);
    }

//      本期计量金额 = 本站点当期计量金额(合价)合计
//     * 累计计量金额 = 已计量期数的本期计量金额合计
//     * 本期支付金额 = 本期计量金额-扣回开工预付金额+奖罚金
//     * 累计支付金额 = 开工预付款-奖励基金 + 已计量期数的本期支付金额合计
    //更新或新增标段站点期数计算值；
    @Override
    @DSTransactional
    public Boolean updateCountBatch(CmBdQsCountBo bo) {
        Long bdId = bo.getBdId();
        Long qsId = bo.getQsId();
        if (bdId == null || qsId == null) {
            return false;
        }
        //查询标段下所有站点；
        List<BaseBsZd> zdList = zdMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId, bo.getBdId()));
        Set<Long> zdSet = zdList.stream().map(BaseBsZd::getId).collect(Collectors.toSet());
        zdSet.forEach(e->{
            CmBdQsCountBo countBo = new CmBdQsCountBo();
            countBo.setBdId(bo.getBdId());
            countBo.setQsId(bo.getQsId());
            countBo.setZdId(e);
            this.update(countBo);
        });
        return true;
    }

//      本期计量金额 = 本站点当期计量金额(合价)合计
//     * 累计计量金额 = 已计量期数的本期计量金额合计
//     * 本期支付金额 = 本期计量金额-扣回开工预付金额+奖罚金
//     * 累计支付金额 = 开工预付款-奖励基金 + 已计量期数的本期支付金额合计
    //更新或新增标段站点期数计算值；
//    @Override
//    @DSTransactional
//    public Boolean updateCountBatch(CmBdQsCountBo bo) {
//        Long bdId = bo.getBdId();
//        Long qsId = bo.getQsId();
//        if (bdId == null || qsId == null) {
//            return false;
//        }
//        //查询标段下所有站点；
//        List<BaseBsZd> zdList = zdMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId, bo.getBdId()));
//        Set<Long> zdSet = zdList.stream().map(BaseBsZd::getId).collect(Collectors.toSet());
//        zdSet.forEach(e->{
//            CmBdQsCountBo countBo = new CmBdQsCountBo();
//            countBo.setBdId(bo.getBdId());
//            countBo.setQsId(bo.getQsId());
//            countBo.setZdId(e);
//            this.update(countBo);
//        });
//        return true;
//    }

//      本期计量金额 = 本站点当期计量金额(合价)合计
//     * 累计计量金额 = 已计量期数的本期计量金额合计
//     * 本期支付金额 = 本期计量金额-扣回开工预付金额+奖罚金
//     * 累计支付金额 = 开工预付款-奖励基金 + 已计量期数的本期支付金额合计
    //更新或新增标段站点期数计算值；
    @Override
    @DSTransactional
    public Boolean updateBatch(CmBdQsCountBo bo) {
        Long bdId = bo.getBdId();
        Long qsId = bo.getQsId();
        if(bdId == null || qsId == null){
            return false;
        }
        CmBsQsVo cmBsQsVo = qsMapper.selectVoById(qsId);
        Integer qs = cmBsQsVo.getSettleIndex();
        //查询标段下所有站点；
        List<BaseBsZd> zdList = zdMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId, bo.getBdId()));
        Set<Long> zdSet = zdList.stream().map(BaseBsZd::getId).collect(Collectors.toSet());
        //根据期数和站点id查询数据
        LambdaQueryWrapper<CmBdQsCount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmBdQsCount::getQs,qs);
        wrapper.in(CmBdQsCount::getZdId,zdSet);
        List<CmBdQsCount> qsCounts = baseMapper.selectList(wrapper);
        //上期所有站点数据 ；
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmBdQsCount::getQs, qs - 1);
        wrapper.in(CmBdQsCount::getZdId,zdSet);
        List<CmBdQsCount> qqsCounts = baseMapper.selectList(wrapper);
        Map<Long, CmBdQsCount> qzdIdCounts = qqsCounts.stream().collect(Collectors.toMap(CmBdQsCount::getZdId, e -> e));
//  1、计算本期计量金额、累计计量金额；
        //查询中间计量列表
        LambdaQueryWrapper<CmPeriodMeasurement> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(CmPeriodMeasurement::getZdId,zdSet);
        lambdaQueryWrapper.eq(CmPeriodMeasurement::getQsId,qsId);
        List<CmPeriodMeasurement> cmPeriodMeasurements = periodMapper.selectList(lambdaQueryWrapper);
        Map<Long, List<CmPeriodMeasurement>> zdPeriodMap = cmPeriodMeasurements.stream().collect(Collectors.groupingBy(CmPeriodMeasurement::getZdId));
        //查询其他计量金额；
        LambdaQueryWrapper<CmBaSettleDeductDetail> qtjlWrapper = new LambdaQueryWrapper<>();
        qtjlWrapper.eq(CmBaSettleDeductDetail::getBdId,bdId);
        qtjlWrapper.eq(CmBaSettleDeductDetail::getQsId,qsId);
        List<CmBaSettleDeductDetail> qtjlList = deductDetailMapper.selectList(qtjlWrapper);
        BigDecimal khkgyfk = BigDecimal.ZERO;
        BigDecimal jfje = BigDecimal.ZERO;
        BigDecimal bqzfje = BigDecimal.ZERO;
        BigDecimal ljzfje;
        if(CollUtil.isEmpty(qsCounts)){
            qsCounts = new ArrayList<>();
            //查询开工预付款
            LambdaQueryWrapper<CmBsStartAdvance> advanceWrapper = new LambdaQueryWrapper<>();
            advanceWrapper.in(CmBsStartAdvance::getZdId,zdSet);
            List<CmBsStartAdvanceVo> kgyfks = advanceMapper.selectVoList(advanceWrapper);
            Map<Long, CmBsStartAdvanceVo> kgyfkMap = kgyfks.stream().collect(Collectors.toMap(CmBsStartAdvanceVo::getZdId, e -> e));
            for(Long zd:zdSet){
                List<CmPeriodMeasurement> measurements = zdPeriodMap.get(zd);
                BigDecimal bqjl = BigDecimal.ZERO;
                for(CmPeriodMeasurement vo :measurements) {
                    if (vo.getTotalPrice() != null) {
                        bqjl = BigDecimalUtil.add(bqjl, vo.getTotalPrice());
                    }
                }
                CmBdQsCount qsCount = new CmBdQsCount();
                qsCount.setQsId(qsId);
                qsCount.setZdId(zd);
                qsCount.setBdId(bdId);
                qsCount.setQs(qs);
                qsCount.setBqjlje(bqjl);
                qsCount.setBqzfje(bqzfje);
                //获取开工预付款
                CmBsStartAdvanceVo advanceVo = kgyfkMap.get(zd);
                BigDecimal kgyfkjr = advanceVo.getKgyfkjr();
                BigDecimal kcjljj = advanceVo.getKcjljj();
                //判断是否是第一期
                if (qs == 1) {
                    qsCount.setLjjlje(bqjl);
                    ljzfje = BigDecimalUtil.add(BigDecimalUtil.subtract(kgyfkjr, kcjljj), bqzfje);
                    qsCount.setLjzfje(ljzfje);
                } else {
                    //如果不是第一期，查询上期的数据；
                    CmBdQsCount qqsCount = qzdIdCounts.get(zd);
                    qsCount.setLjjlje(BigDecimalUtil.add(bqjl, qqsCount == null ? BigDecimal.ZERO : qqsCount.getLjjlje()));
                    ljzfje = BigDecimalUtil.add(BigDecimalUtil.subtract(kgyfkjr, kcjljj), BigDecimalUtil.subtract(qqsCount == null ? BigDecimal.ZERO : qqsCount.getLjzfje(), bqzfje));
                    qsCount.setLjzfje(ljzfje);
                }
                qsCounts.add(qsCount);
            }
            //批量新增标段、站点、期数计算数据；
//            baseMapper.insertBatch(qsCounts);
        } else {
            for(CmBdQsCount qsCount:qsCounts) {
                if (CollUtil.isNotEmpty(qtjlList)) {
                    List<CmBaSettleDeductDetail> qtjlLists = qtjlList.stream().filter(e -> qsCount.getZdId().equals(e.getZdId())).collect(Collectors.toList());
                    for (CmBaSettleDeductDetail qtjl : qtjlLists) {
                        //扣回开工预付款；
                        if ("2".equals(qtjl.getDeductType())) {
                            khkgyfk = qtjl.getDeductDetailMoney() == null ? BigDecimal.ZERO : qtjl.getDeductDetailMoney();
                        }
                        //奖罚金额；
                        if ("1".equals(qtjl.getDeductType())) {
                            jfje = qtjl.getDeductDetailMoney() == null ? BigDecimal.ZERO : qtjl.getDeductDetailMoney();
                        }
                    }
                    bqzfje = BigDecimalUtil.add(BigDecimalUtil.subtract(qsCount.getBqjlje(), khkgyfk), jfje);
                }
                List<CmPeriodMeasurement> measurements = zdPeriodMap.get(qsCount.getZdId());
                BigDecimal bqjl = BigDecimal.ZERO;
                for(CmPeriodMeasurement vo :measurements) {
                    if (vo.getTotalPrice() != null) {
                        bqjl = BigDecimalUtil.add(bqjl, vo.getTotalPrice());
                    }
                }
                qsCount.setBqjlje(bqjl);
                BigDecimal ljjl = BigDecimalUtil.add(bqjl, BigDecimalUtil.subtract(qsCount.getLjjlje(), qsCount.getBqjlje()));
                qsCount.setLjjlje(ljjl);
                qsCount.setBqzfje(bqzfje);
                qsCount.setLjzfje(BigDecimalUtil.add(bqzfje, BigDecimalUtil.subtract(qsCount.getLjzfje(), qsCount.getBqzfje())));
            }

        }
        return baseMapper.insertOrUpdateBatch(qsCounts);
    }

    //报表管理
    //先根据标段id，期数id查询报表数据
    @Override
    public List<ReportVo> getReportInfo(CmBdQsCountBo bo) {
        Long bdId = bo.getBdId();
        Long qsId = bo.getQsId();
        if(bdId == null || qsId == null){
            return new ArrayList<>();
        }
        //查询站点信息；
        List<BaseBsZd> zdList = zdMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId,bdId));
        if(CollUtil.isEmpty(zdList)){
            return new ArrayList<>();
        }
        //1.查询标段下的所有期数；
        List<CmBsQs> qsList = qsMapper.selectList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId,bdId));
        if(CollUtil.isEmpty(qsList)){
            return new ArrayList<>();
        }
        Set<Long> zdIds = zdList.stream().map(BaseBsZd::getId).collect(Collectors.toSet());
        List<ReportVo> reportVos = new ArrayList<>();
        //报表审批状态；
        String status="";
        //查询报表管理数据
        List<CmReport> cmReports = reportMapper.selectList(new LambdaQueryWrapper<CmReport>().eq(CmReport::getBdId,bdId).eq(CmReport::getQsId,qsId)
            .in(CmReport::getZdId,zdIds).eq(CmReport::getDelFlag,"0"));
        if(CollUtil.isNotEmpty(cmReports)) {
            //根据站点去重；
            cmReports = new ArrayList<>(cmReports.stream().collect(Collectors.toMap(CmReport::getZdId, report -> report, (a, b) -> a)).values());
            status = cmReports.get(0).getStatus() == null ? "00" : cmReports.get(0).getStatus();
            //如果审批状态为审批中或者已审批，直接返回报表管理数据信息，否则重新计算；
            if ("11".equals(status) || "22".equals(status)) {
                for (CmReport cmReport : cmReports) {
                    ReportVo reportVo = new ReportVo();
                    BeanUtil.copyProperties(cmReport, reportVo); // 拷贝属性
                    reportVos.add(reportVo);
                }
                return reportVos;
            }
        }
        //本期期数；
        Integer qs = qsList.stream().filter(e -> qsId.equals(e.getQsId())).collect(Collectors.toList()).get(0).getSettleIndex();
        Set<Long> qqsIdSet = qsList.stream().filter(e -> e.getSettleIndex() <= qs).map(CmBsQs::getQsId).collect(Collectors.toSet());
        //查询开工预付款
        //往期开工预付款(=本期及之前所有期次的)
        CmBsStartAdvanceVo wkgyfk = null ;
        //往期开工预付款(=本期之前所有期次的,不包含本期)
        CmBsStartAdvanceVo wwkgyfk = null ;
        CmBsStartAdvanceBo advanceBo = new CmBsStartAdvanceBo();
        advanceBo.setBdId(bdId);
        //本标段的开工预付款(所有期次)；
        List<CmBsStartAdvanceVo> advanceVos = advanceService.listData(advanceBo);
        //往期的开工预付款(包含本期)；
        List<CmBsStartAdvanceVo> qAdvanceVos = advanceVos.stream().filter(e->qqsIdSet.contains(e.getQsId())).collect(Collectors.toList());
        //往期的开工预付款(不包含本期)；
        List<CmBsStartAdvanceVo> wAdvanceVos = advanceVos.stream().filter(e->qqsIdSet.contains(e.getQsId()) && !qsId.equals(e.getQsId())).collect(Collectors.toList());
        //本期开工预付款
        List<CmBsStartAdvanceVo> advanceVoList = advanceVos.stream().filter(e->qsId.equals(e.getQsId())).collect(Collectors.toList());
        //查询站点期数计算；
        LambdaQueryWrapper<CmBdQsCount> bdqscountWrapper = new LambdaQueryWrapper<>();
        bdqscountWrapper.eq(CmBdQsCount::getQsId,qsId);
        bdqscountWrapper.eq(CmBdQsCount::getBdId,bdId);
        List<CmBdQsCount> cmBdQsCounts = baseMapper.selectList(bdqscountWrapper);
        //如果中间计量计算值缺少，重新计算一次；
        if(zdList.size() != cmBdQsCounts.size()){
            for(BaseBsZd zd :zdList){
                CmBdQsCountBo countBo = new CmBdQsCountBo();
                countBo.setBdId(bdId);
                countBo.setQsId(qsId);
                countBo.setZdId(zd.getId());
                this.update(countBo);
            }
            cmBdQsCounts = baseMapper.selectList(bdqscountWrapper);
        }
        Map<Long, CmBdQsCount> bdQsCountMap = cmBdQsCounts.stream().collect(Collectors.toMap(CmBdQsCount::getZdId, e -> e));
        //查询其他计量；
        LambdaQueryWrapper<CmBaSettleDeductDetail> lqw = new LambdaQueryWrapper();
        lqw.eq(CmBaSettleDeductDetail::getBdId,bdId);
        List<CmBaSettleDeductDetail> deductDetails = deductDetailMapper.selectList(lqw);
        Map<Long, List<CmBaSettleDeductDetail>> allDeductDetailMap = deductDetails.stream().collect(Collectors.groupingBy(CmBaSettleDeductDetail::getZdId));
        Map<Long, List<CmBaSettleDeductDetail>> deductDetailMap = deductDetails.stream().filter(e->qsId.equals(e.getQsId())).collect(Collectors.groupingBy(CmBaSettleDeductDetail::getZdId));
        Map<Long, List<CmBaSettleDeductDetail>> wdeductDetailMap = deductDetails.stream().filter(e->qqsIdSet.contains(e.getQsId())).collect(Collectors.groupingBy(CmBaSettleDeductDetail::getZdId));
        //组装返回数据；
        for(BaseBsZd e : zdList){
            Long zdId = e.getId();
            ReportVo vo = new ReportVo();
            BeanUtil.copyProperties(e,vo);
            vo.setZdId(e.getId());
            vo.setQsId(qsId);
            if (ObjectUtil.isNotEmpty(e.getJiansrlActual())) {  // 改为千瓦
                BigDecimal jiansrl = e.getJiansrlActual().divide(new BigDecimal(1000));
                vo.setJiansrl(jiansrl);
            } else {
                vo.setJiansrl(e.getJiansrlActual());
            }
//            vo.setJiansrl(e.getJiansrlActual());
            reportVos.add(vo);
            //开工预付款；
            if(CollUtil.isNotEmpty(qAdvanceVos)){
                List<CmBsStartAdvanceVo> collect = qAdvanceVos.stream().filter(item -> zdId.equals(item.getZdId())).collect(Collectors.toList());
                if(CollUtil.isNotEmpty(collect)){
                    wkgyfk = collect.get(0);
                }
            }
            BigDecimal kgyfkjr = BigDecimal.ZERO;
            BigDecimal kcjljj = BigDecimal.ZERO;
            if(wkgyfk!=null){
                kgyfkjr = wkgyfk.getKgyfkjr() == null? BigDecimal.ZERO:wkgyfk.getKgyfkjr();
                kcjljj = wkgyfk.getKcjljj() == null?BigDecimal.ZERO:wkgyfk.getKcjljj();
            }
            wkgyfk = null;

            //往期开工预付款；不包含本期
            if(CollUtil.isNotEmpty(wAdvanceVos)){
                List<CmBsStartAdvanceVo> collect = wAdvanceVos.stream().filter(item -> zdId.equals(item.getZdId())).collect(Collectors.toList());
                if(CollUtil.isNotEmpty(collect)){
                    wwkgyfk = collect.get(0);
                }
            }
            BigDecimal wkgyfkjr = BigDecimal.ZERO;
            BigDecimal wkcjljj = BigDecimal.ZERO;
            if(wwkgyfk!=null){
                wkgyfkjr = wwkgyfk.getKgyfkjr() == null? BigDecimal.ZERO:wwkgyfk.getKgyfkjr();
                wkcjljj = wwkgyfk.getKcjljj() == null?BigDecimal.ZERO:wwkgyfk.getKcjljj();
            }
            wwkgyfk = null;


            //单站点总价
            BigDecimal zdContractAmountActual = e.getZdContractAmountActual();
            //判断是否计量过；
            List<CmPeriodMeasurement> measurements = periodMapper.selectList(new LambdaQueryWrapper<CmPeriodMeasurement>().eq(CmPeriodMeasurement::getZdId, zdId).in(CmPeriodMeasurement::getQsId, qqsIdSet));
            BigDecimal jlje = BigDecimal.ZERO;
            if (CollUtil.isNotEmpty(measurements)) {
                for (CmPeriodMeasurement period : measurements) {
                    jlje = BigDecimalUtil.add(jlje, period.getTotalPrice());
                }
                if (jlje.compareTo(BigDecimal.ZERO) == 0) {
                    zdContractAmountActual = e.getZdContractAmount();
                }
            } else {
                zdContractAmountActual = e.getZdContractAmount();
            }
            vo.setDanzdzj(zdContractAmountActual);
            //变动后价格
            vo.setChgPrice(e.getChgPrice());
//            if(e.getDanwzj()!=null&&e.getJiansrl()!=null){
//                vo.setJiansrl(BigDecimalUtil.divide(e.getJiansrl(),BigDecimal.valueOf(1000),4));
//                BigDecimal zdContractAmountActual = e.getZdContractAmountActual();
//                vo.setDanzdzj(BigDecimalUtil.multiply(e.getDanwzj(),e.getJiansrl()));
//            } else {
//                vo.setDanzdzj(BigDecimal.ZERO);
//            }
            //已支付预付款
//            BigDecimal yfk = BigDecimalUtil.subtract(kgyfkjr, kcjljj);
//            vo.setYizfyfk(yfk);
            BigDecimal yfk = BigDecimalUtil.subtract(wkgyfkjr, wkcjljj);
            vo.setYizfyfk(yfk);
            //累计扣除预付款=往期其他计量里的扣回开工预付款的和；
            //其他计量往期奖罚金额之和；
            BigDecimal ljkcyfk = BigDecimal.ZERO;
            BigDecimal ljjfje = BigDecimal.ZERO;
            if(CollUtil.isNotEmpty(wdeductDetailMap.get(e.getId()))){
                List<CmBaSettleDeductDetail> deductDetails1 = wdeductDetailMap.get(e.getId()).stream().filter(item->"2".equals(item.getDeductType())).collect(Collectors.toList());
                List<CmBaSettleDeductDetail> deductDetails2 = wdeductDetailMap.get(e.getId()).stream().filter(item->"1".equals(item.getDeductType())).collect(Collectors.toList());
                if(CollUtil.isNotEmpty(deductDetails1)){
                    for(CmBaSettleDeductDetail deductDetail:deductDetails1){
                        ljkcyfk = BigDecimalUtil.add(ljkcyfk,deductDetail.getDeductDetailMoney());
                    }
                }
                //奖罚金额之和；
                if(CollUtil.isNotEmpty(deductDetails2)){
                    for(CmBaSettleDeductDetail deductDetail:deductDetails2){
                        ljjfje = BigDecimalUtil.add(ljjfje,deductDetail.getDeductDetailMoney());
                    }
                }
            }
            vo.setLeijkcyfk(ljkcyfk);

            //本次扣款金额=本期开工预付款扣除奖励基金-其他计量里的奖罚金额；
            if(CollUtil.isNotEmpty(advanceVoList)) {
                List<CmBsStartAdvanceVo> advanceVo = advanceVoList.stream().filter(start -> start.getZdId().equals(e.getId())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(advanceVo)) {
                    CmBsStartAdvanceVo advanceVo1 = advanceVo.get(0);
                    vo.setBenckkje(advanceVo1.getKcjljj());
                }
            }
            //其他计量的奖罚金额；
            BigDecimal benckkje = vo.getBenckkje() == null ? BigDecimal.ZERO:vo.getBenckkje();
            List<CmBaSettleDeductDetail> deductDetails1 = deductDetailMap.get(e.getId());
            if(CollUtil.isNotEmpty(deductDetails1)) {
                deductDetails1 = deductDetails1.stream().filter(o -> "1".equals(o.getDeductType())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(deductDetails1)) {
                    CmBaSettleDeductDetail deductDetail = deductDetails1.get(0);
                    BigDecimal deductDetailMoney = deductDetail.getDeductDetailMoney() == null ? BigDecimal.ZERO : deductDetail.getDeductDetailMoney();
                    vo.setBenckkje(BigDecimalUtil.subtract(benckkje, deductDetailMoney));
                }
            }


            //累计扣款金额= 往期开工预付款里的奖励基金之和-往期其他计量里的奖罚金额之和；
            vo.setLeijkkje(BigDecimalUtil.subtract(kcjljj,ljjfje));

            //本次付款金额 =本期支付金额 ；累计付款 = 累计支付金额；截止上次累计支付 = 累计支付-本次付款；
            if(CollUtil.isNotEmpty(bdQsCountMap)&&bdQsCountMap.get(zdId)!=null){
                vo.setBencfkje(bdQsCountMap.get(zdId).getBqzfje());
                vo.setJiezbcljfkje(bdQsCountMap.get(zdId).getLjzfje());
                vo.setJiezscljfkje(BigDecimalUtil.subtract(bdQsCountMap.get(zdId).getLjzfje(),bdQsCountMap.get(zdId).getBqzfje()));
            }
            //付款比例
            if(zdContractAmountActual != null && zdContractAmountActual.compareTo(BigDecimal.ZERO) != 0){
                vo.setFukbl(BigDecimalUtil.divide(BigDecimalUtil.add(vo.getLeijkkje(),vo.getJiezbcljfkje()),zdContractAmountActual));
            } else {
                vo.setFukbl(BigDecimal.ZERO);
            }
        }

        //（处理历史数据问题；）如果为空，就持久化
        if(CollUtil.isEmpty(cmReports)) {
            List<CmReport> cmReports1 = reportMapper.selectList(new LambdaQueryWrapper<CmReport>().eq(CmReport::getBdId, bdId).eq(CmReport::getQsId, qsId));
            if(CollUtil.isNotEmpty(cmReports1)){
                String status1 = cmReports1.get(0).getStatus();
                //如果审批状态为审批中或者已审批,就持久化报表数据；
                if ("11".equals(status1) || "22".equals(status1)) {
                    for(ReportVo reportVo:reportVos){
                        CmReport cmReport = new CmReport();
                        BeanUtil.copyProperties(reportVo, cmReport); // 拷贝属性
                        cmReport.setStatus(status1);
                        cmReport.setId(null);
                        cmReports.add(cmReport);
                    }
                    reportMapper.insertBatch(cmReports);
                }
            }
        }
        return reportVos;
    }

    //获取开票汇总列表；
    @Override
    @DSTransactional
    public List<CmBdQsCountVo> getInvoiceSummary(CmBdQsCountBo bo) {
        if(bo.getBdId() == null || bo.getQsId() == null){
            return new ArrayList<>();
        }
        //查询站点信息；
        LambdaQueryWrapper<BaseBsZd> wrapper = new LambdaQueryWrapper();
        wrapper.eq(BaseBsZd::getBdId,bo.getBdId());
        List<BaseBsZd> zdList = zdMapper.selectList(wrapper);
        Map<Long, BaseBsZd> zdMap = zdList.stream().collect(Collectors.toMap(BaseBsZd::getId, e -> e));
        if(CollUtil.isEmpty(zdList)){
            return new ArrayList<>();
        }
        //查询标段站点期数计算数据
        LambdaQueryWrapper<CmBdQsCount> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(CmBdQsCount::getBdId,bo.getBdId());
        countWrapper.eq(CmBdQsCount::getQsId,bo.getQsId());
        countWrapper.orderByAsc(CmBdQsCount::getZdId);
        List<CmBdQsCountVo> cmBdQsCounts = baseMapper.selectVoList(countWrapper);
        if(CollUtil.isEmpty(cmBdQsCounts)||zdList.size() != cmBdQsCounts.size()) {
            //如果站点数和计量数不等；先删后计算；
            if(CollUtil.isNotEmpty(cmBdQsCounts) && zdList.size() != cmBdQsCounts.size()){
                Set<Long> countids = cmBdQsCounts.stream().map(CmBdQsCountVo::getId).collect(Collectors.toSet());
                baseMapper.deleteBatchIds(countids);
            }
            //如果中间计量计算值缺少，重新计算一次；
//            updateCountBatch(bo);
            zdList.forEach(e->{
                CmBdQsCountBo countBo = new CmBdQsCountBo();
                countBo.setBdId(bo.getBdId());
                countBo.setQsId(bo.getQsId());
                countBo.setZdId(e.getId());
                this.update(countBo);
            });
            cmBdQsCounts = baseMapper.selectVoList(countWrapper);
        }
        return generateData(cmBdQsCounts, zdMap, bo);
    }

    /**
     * 获取支付统计列表；
     * @param bo
     * @return
     */
    @Override
    public Map<String, List<Map<String, String>>> getPaymentList(CmBdQsCountBo bo) {
        Long bdId = bo.getBdId();
        if (bdId == null) {
            return new HashMap<>();
        }
        Map<String, List<Map<String, String>>> returnMap = new HashMap<>();
        List<Map<String, String>> titleList = new ArrayList<>();
        List<Map<String, String>> list = new ArrayList<>();
        returnMap.put("titleList", titleList);
        returnMap.put("list", list);
        //查询标段下的站点；
        List<BaseBsZd> zdList = zdMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId,bdId));
        if(CollUtil.isEmpty(zdList)){
            return new HashMap<>();
        }
        //查询标段下的期数；
        List<CmBsQs> qsList = qsMapper.selectList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId, bdId).orderByAsc(CmBsQs::getSettleIndex));
        if(CollUtil.isEmpty(qsList)){
            return new HashMap<>();
        }
        Long firstQsId = qsList.stream().filter(e->e.getSettleIndex() == 1).findFirst().get().getQsId();
        for(CmBsQs qs : qsList){
            Map<String,String> map = new HashMap<>();
            map.put("label","第"+qs.getSettleIndex()+"次支付");
            map.put("value","payment"+qs.getSettleIndex());
            map.put("qsId",qs.getQsId().toString());
            titleList.add(map);
        }
        //查询标段的开工预付款；
        List<CmBsStartAdvance> advances = advanceMapper.selectList(new LambdaQueryWrapper<CmBsStartAdvance>().eq(CmBsStartAdvance::getBdId,bdId));
        Map<Long, List<CmBsStartAdvance>> qskgyfkMap = advances.stream().filter(e->e.getQsId()!=null).collect(Collectors.groupingBy(CmBsStartAdvance::getQsId));
        List<CmBsStartAdvance> firstQsAdvanceList = qskgyfkMap.get(firstQsId);
        //查询标段的中间计量数据；
        List<CmBdQsCount> qsCounts = baseMapper.selectList(new LambdaQueryWrapper<CmBdQsCount>().eq(CmBdQsCount::getBdId,bdId));
        Map<Long, List<CmBdQsCount>> zdqscountMap = qsCounts.stream().collect(Collectors.groupingBy(CmBdQsCount::getZdId));
        for(BaseBsZd zd : zdList) {
            List<CmBdQsCount> qsCountsList = zdqscountMap.get(zd.getId());
            Map<String, String> map = new HashMap<>();
            map.put("zdName", zd.getName());
            map.put("contractAcount", zd.getZdContractAmount() == null ? "0.00" : zd.getZdContractAmount().toPlainString());
            map.put("actualContractAmount", zd.getZdContractAmountActual() == null ? "0.00" : zd.getZdContractAmountActual().toPlainString());
            String kgyfk="0.00";
            if(CollUtil.isNotEmpty(firstQsAdvanceList)){
                CmBsStartAdvance advance = firstQsAdvanceList.stream().filter(e -> e.getZdId().equals(zd.getId())).findFirst().orElseGet(() -> new CmBsStartAdvance());
                kgyfk = advance.getKgyfkjr() != null ? advance.getKgyfkjr().toPlainString() : "0.00";
            }
            map.put("kgyfk", kgyfk);
            //合计
            BigDecimal total = new BigDecimal(kgyfk);
            for (Map<String, String> maps : titleList) {
                Long qsId = Long.valueOf(maps.get("qsId"));
                if(CollUtil.isNotEmpty(qsCountsList)){
                    BigDecimal values = qsCountsList.stream().filter(e -> e.getQsId().equals(qsId)).findFirst().orElseGet(()->new CmBdQsCount()).getBqzfje();
                    String value = values == null ? "0.00" : values.toPlainString();
                    map.put(maps.get("value"), value);
                    total = total.add(new BigDecimal(value));
                } else {
                    map.put(maps.get("value"),"0.00");
                }
            }
            map.put("total", total.toPlainString());
            list.add(map);
        }
        return returnMap;
    }

    //组装返回数据；
    private List<CmBdQsCountVo> generateData(List<CmBdQsCountVo> cmBdQsCounts,Map<Long, BaseBsZd> zdMap,CmBdQsCountBo bo) {

        //查出标段下第一期期数id；
        List<CmBsQs> qsList = qsMapper.selectList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId, bo.getBdId()));
        Long qsId = qsList.stream().filter(e -> e.getSettleIndex() == 1).findFirst().get().getQsId();
//        //查询标段下第一期期数的计算数据；
        LambdaQueryWrapper<CmBdQsCount> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(CmBdQsCount::getBdId,bo.getBdId());
        countWrapper.eq(CmBdQsCount::getQsId,qsId);
        List<CmBdQsCount> firstQsCounts = baseMapper.selectList(countWrapper);
        Map<Long, CmBdQsCount> zdQsCountMap = firstQsCounts.stream().collect(Collectors.toMap(CmBdQsCount::getZdId,e->e));
        cmBdQsCounts.forEach(e -> {
            e.setDyckpje(zdQsCountMap.get(e.getZdId()).getBqjlje());
            //已支付金额；=累计支付金额-本期支付金额；
            BigDecimal yzfje = BigDecimal.ZERO;
            if(e.getLjzfje()!=null&&e.getBqzfje()!=null){
                yzfje = BigDecimalUtil.subtract(e.getLjzfje(),e.getBqzfje());
            }
            e.setYzfje(yzfje);
            e.setZdhjyzfje(yzfje);
            e.setZdhjbqzfje(e.getBqzfje());
            e.setZdhjljzfje(e.getLjzfje());
            e.setBckpje(e.getBqjlje());
            e.setDkpje(BigDecimalUtil.subtract(e.getLjjlje(),e.getLjzfje()));
            e.setZdName(zdMap.get(e.getZdId()) == null ? "":zdMap.get(e.getZdId()).getName());
        });
        return cmBdQsCounts;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CmBdQsCount entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除标段期数计算
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

}
